package com.gaussian.property.admin.module.system.service;

import com.songqi.common.core.constant.Constants;
import com.songqi.common.core.enums.UserStatus;
import com.songqi.common.core.exception.user.AccountAuthenticationException;
import com.songqi.common.core.utils.StringUtils;
import com.songqi.common.security.model.LoginUser;
import com.gaussian.property.module.system.entity.SysUser;
import com.gaussian.property.module.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 用户验证处理
 *
 * @author songqi(13776346982)
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService
{
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Resource
    private ISysUserService userService;

    @Resource
    private SysPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException
    {
        SysUser user = userService.selectUserByUserName(username);
        if (StringUtils.isNull(user))
        {
            log.info("登录用户：{} 不存在.", username);
            throw new UsernameNotFoundException("用户不存在");
        }
        else if (Constants.YES_FLAG.equals(user.getDelFlag()))
        {
            log.info("登录用户：{} 已被删除.", username);
            throw new AccountAuthenticationException("对不起，您的账号已被删除");
        }
        else if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            log.info("登录用户：{} 已被停用.", username);
            throw new AccountAuthenticationException("用户已停用，请联系管理员");
        }

        return createLoginUser(user);
    }

    public UserDetails createLoginUser(SysUser user)
    {
        return new LoginUser(user, permissionService.getMenuPermission(user));
    }
}
